package com.example.untils;

import com.example.common.enums.ResultCodeEnum;
import com.example.entity.vo.User.DscmaVo;
import com.example.entity.yifei.Dscma;
import com.example.exception.CustomException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class JwtUtils {


    // 单位是毫秒
    public static final long EXPIRE = 60 * 60 * 8 * 1000;
    // 密钥
    public static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHOukc8BDbRigUDaY6pZFfWus2jZW";

    public static String getJwtToken(DscmaVo dscma){
        String JwtToken = Jwts.builder()
                .setHeaderParam("typ", "JWT")   // 设置头信息
                .setHeaderParam("alg", "HS256")
                .setSubject("hz-user")
                .setIssuedAt(new Date())   // 设置过期时间
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .claim("MA001", dscma.getMa001())  // 设置token主体部分
//                .claim("nickname", nickname)
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();

        return JwtToken;
    }

    /**
     * 判断token是否存在与有效
     * @param jwtToken
     * @return
     */
    public static boolean checkToken(String jwtToken) {

        if(StringUtils.isEmpty(jwtToken)) return false;
        try {
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * 判断token是否存在与有效
     * @param request
     * @return
     */

    public static boolean checkToken(HttpServletRequest request){

        try {
            String jwtToken = request.getHeader("token");
            if(StringUtils.isEmpty(jwtToken)) {
                return false;
            }
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);

        } catch (Exception e) {

            e.printStackTrace();
//            throw new CustomException(ResultCodeEnum.TOKEN_CHECK_ERROR);
            return false;
        }
        return true;
    }

    /**
     * 根据token获取MA001
     * @param request
     * @return
     */

    public static String getMA001ByJwtToken(HttpServletRequest request) {

        String jwtToken = request.getHeader("token");
        if(StringUtils.isEmpty(jwtToken)) return "";
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        Claims claims = claimsJws.getBody();
        return (String)claims.get("MA001");

    }

//    public static void main(String[] args) {
//        String jwtToken = getJwtToken("123456");
//        System.out.println(jwtToken);
//    }

}